package com.travel.server.manager.impl.command.project;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.project.AddProjectGroupRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.GroupDal;
import com.travel.server.manager.impl.dal.GroupDal.GroupParam;
import com.travel.server.manager.model.ProjectGroup;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/26 17:40
 * @Desc:
 */
@Component
@Slf4j
public class AddProjectGroupCommand extends AbstractCommand<AddProjectGroupRequest, EmptyResponse> {

    @Autowired
    private GroupDal groupDal;

    @Override
    protected void checkInput(AddProjectGroupRequest request) {

    }

    @Override
    public EmptyResponse handle(AddProjectGroupRequest request) {
        checkInput(request);

        GroupParam param = new GroupParam();
        param.setName(request.getGroupName());
        List<ProjectGroup> list = groupDal.selectByExample(param);
        if(!CollectionUtil.isEmpty(list)){
            throw new WorkException(WorkCode.EXIST_SAME_NAME);
        }

        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        ProjectGroup projectGroup = new ProjectGroup();
        projectGroup.setNumber(request.getNumber());
        projectGroup.setName(request.getGroupName());
        projectGroup.setState(CommonConstant.YES);
        projectGroup.setParentClass(request.getParentClass());
        projectGroup.setCreateBy(userInfo.getName());
        projectGroup.setUpdateBy(userInfo.getName());
        projectGroup.setCreateTime(now);
        projectGroup.setUpdateTime(now);

        groupDal.updateOrInsert(projectGroup);
        return new EmptyResponse();
    }
}
